import { goPage } from "./commonFn";

// api.ts
export const BASE_URL = "https://api.zrencai.com"; // 你的接口基础URL
// export const BASE_URL = "http://47.97.178.250:8081"; // 你的接口基础URL
export const BASE_UPLOADURL = BASE_URL + "/infra/file/upload"; // 上传图片
export const BASE_CLOUDUPLOADURL = BASE_URL + "/infra/file/uploadCloudFile"; // 云盘上传图片

// 统一的异常处理函数
function handleRequestError(error: any) {
  uni.showToast({
    title: error || "网络请求失败",
    icon: "none",
    duration: 3000,
  });
  console.error("请求失败：", error);
}
type commonApiResponse<T> = commonTypes.ApiResponse<T> | commonTypes.ApiRowResponse<T>;
// 发送请求的封装
export function apiRequest<T>(config: any): any {
  config.url = `${BASE_URL}${config.url}`;
  config.header = {
    Authorization: uni.getStorageSync("token"),
  };
  let thePages: any = getCurrentPages();
  const pageName = thePages[thePages.length - 1].route;
  if (
    pageName !== "pages/home/home" &&
    pageName !== "pages/cloudStorage/cloudStorage" &&
    pageName !== "pages/home/compressPage" &&
    pageName !== "pages/entertainment/entertainment" &&
    pageName !== "pages/cloudStorage/filesDetails"
  ) {
    uni.showLoading({
      title: "加载中",
    });
  }
  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success(response: { data: commonApiResponse<T> }) {
        const data = response.data;
        if (
          pageName !== "pages/home/home" &&
          pageName !== "pages/cloudStorage/cloudStorage" &&
          pageName !== "pages/home/compressPage" &&
          pageName !== "pages/entertainment/entertainment" &&
          pageName !== "pages/cloudStorage/filesDetails"
        ) {
          uni.hideLoading();
        }
        if (config.responseType === "arraybuffer") {
          resolve(data);
          return;
        }
        if (data.code === 200) {
          resolve(data);
        } else {
          uni.hideLoading();
          if (data.code === 401) {
            uni.showModal({
              title: "提示",
              cancelText: "否",
              confirmText: "是",
              content: "您当前还未登录，是否前往",
              success: function (res) {
                if (res.confirm) {
                  goPage("/pages/myPage/login");
                }
                if (res.cancel) {
                  uni.switchTab({
                    url: "/pages/home/home",
                  });
                }
              },
            });
            return;
          }
          handleRequestError(data.msg);
          reject(data);
        }
      },
      fail(error: any) {
        uni.hideLoading();
        // 统一异常处理
        console.log(error, "1222222");
        handleRequestError(error.msg);
        reject(error);
      },
    });
  });
}
